<template>

	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item class="syy">公益中心</el-breadcrumb-item>
	</el-breadcrumb>


	<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
		<el-form-item label="文章名">
			<!--  clearable 清除 -->
			<el-input v-model="queryInfo.title" placeholder="请输入文章名" clearable @clear="queryDataList()" />
		</el-form-item>

		<el-form-item label="选择作者">
			<el-select v-model="queryInfo.counselorId" placeholder="请选择作者" clearable @clear="queryDataList()">
				<el-option v-for="item in authorOptions" :key="item.id" :label="item.counselorName" :value="item.id" />
			</el-select>
		</el-form-item>


		<el-form-item>
			<!-- //搜索功能实现主要是queryInfo封装的好，前端输入框输入的数据恰好可以让queryInfo中有值，然后传递到后端，这里输入框双向数据绑定了 -->
			<el-button type="primary" @click="queryDataList()">搜索</el-button>
			<el-button type="primary" @click="add()"> 新增 </el-button>
			<el-button type="danger" @click="batchRemove()">批量删除</el-button>
		</el-form-item>

		<el-table ref="multipleTableRef" :data="dataList" row-key="id" style="width: 100%"
			@selection-change="handleSelectionChange">
			<el-table-column fixed="left" type="selection" width="55" />
			<el-table-column fixed="left" property="id" label="Id" width="60" />
			//省略了scope.row
			<el-table-column property="title" label="文章名" />
			<el-table-column prop="intro" label="文章简介">
				<template #default="scope">
					<div class="simple">{{scope.row.intro}}</div>
				</template>
			</el-table-column>
			<!-- <el-table-column class="simple" property="intro" label="文章简介" /> -->
			<el-table-column property="counselor.counselorName" label="咨询师名" />

			<el-table-column property="listView" label="缩略图">
				<template #default="scope">
					<el-avatar shape="square" size="large" :src="scope.row.listView"></el-avatar>
				</template>
			</el-table-column>

			<el-table-column property="createTime" label="创建时间" />



			<el-table-column fixed="right" label="操作" min-width="120">
				<template #default="scope">
					<!-- 当点击"编辑"按钮时，scope.row 会将当前行的完整数据（如 { id: 1, name: "张三", ... }）传给 edit 方法
如果去掉 scope.row，方法将无法知道要编辑哪一行 -->
					<el-button type="primary" @click="edit(scope.row)" size="small">
						编辑
					</el-button>
					<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
					<el-button type="primary" size="small" @click="check(scope.row)">查看详情内容</el-button>
				</template>
			</el-table-column>
		</el-table>
	</el-form>


	<div class="demo-pagination-block">
		<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
			:page-sizes="[3, 5, 10]" :size="default" layout="total, sizes, prev, pager, next, jumper"
			:total="totalNumber" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
	</div>

	<el-dialog :title="title" v-model="dialogVisible" width="950" @close="cancle()">
		<el-form :model="counselorData" label-width="100">
			<el-form-item label="文章标题">
				<el-input v-model="counselorData.title" autocomplete="off" placeholder="请输入文章标题"></el-input>
			</el-form-item>
			<el-form-item label="文章简介">
				<el-input v-model="counselorData.intro" autocomplete="off" placeholder="请输入文章简介"></el-input>
			</el-form-item>
			<el-form-item label="咨询师作者">
				<el-select v-model="counselorData.counselorId" placeholder="请选择作者" clearable>
					<el-option v-for="item in authorOptions" :key="item.id" :label="item.counselorName"
						:value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="缩略图">
				<el-upload>
					<el-icon>
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>

			<el-form-item label="文章内容详情" prop="content">
				<Editor v-model="counselorData.content" api-key="xd3env9x2gzjdo6ceaxvt31icnchvb8l681otf3u6ogprz04"
					:init="editorConfig" />
			</el-form-item>

		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle()">取 消</el-button>
				<el-button type="primary" @click="confirm()">
					确 定
				</el-button>
			</div>
		</template>
	</el-dialog>

	<el-dialog :title="title" v-model="dialogVisibleCheck" width="950" @close="cancle()">

		<el-form-item label="文章内容详情" prop="content">
			<Editor v-model="counselorData.content" api-key="xd3env9x2gzjdo6ceaxvt31icnchvb8l681otf3u6ogprz04"
				:init="editorConfig" disabled />
		</el-form-item>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancleCheck()">关闭</el-button>
			</div>
		</template>
	</el-dialog>


</template>

<script lang='ts' setup>
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus';
	import {
		reactive,
		ref,
		getCurrentInstance,
		onMounted
	} from 'vue';
	import {
		Plus
	} from '@element-plus/icons-vue'
	import type {
		UploadProps,
		UploadUserFile
	} from 'element-plus'

	const editorConfig = {
		height: 500,
		menubar: true,
		plugins: 'lists link image table code help',
		toolbar: 'undo redo | formatselect | bold italic | alignleft aligncenter alignright | bullist numlist | removeformat',
		skin: 'oxide', // 可选：'oxide-dark' 暗黑模式
		content_css: 'default' // 可选：'dark' 暗黑模式
	}

	//查询信息对象，在payload看
	const queryInfo = reactive({
		title: '',
		counselorId: '',
		pageNum: 1,
		pageSize: 10,
		id: ''
	});
	const authorOptions = ref([]);

	const totalNumber = ref(0);
	//复选的数据,这里用ref不用reactive原因是ref会加上value，这样改变的是value的值，而不是这个变量的值，因为const是定义常量 */
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		//这里只返回选中数据的id
		multipleSelection.value = val.map((item) => {
			return item.id;
		});
	};

	// 每页数量改变
	const handleSizeChange = (val: number) => {
		queryDataList();
	}
	//当前页码改变
	const handleCurrentChange = (val: number) => {
		queryDataList();
	}
	//当前页的数据
	const dataList = ref([]);
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;
	const queryDataList = () => {
		axios.get('welfareCenter/page', {
			params: queryInfo
		}).then((resp) => {
			if (resp.code == 200) {
				dataList.value = resp.data.list;
				totalNumber.value = resp.data.total;
			} else {
				ElMessage.error('查询失败');
			}
			console.log(resp);
		})
	};
	const queryInfoCounselor = reactive({
		counselorName: '',
		counselorGradeId: '',
		pageNum: 1,
		pageSize: ''
	});
	const fetchAuthors = () => {
		axios.get('counselor', {
			// params: queryInfoCounselor
		}).then((resp) => {
			if (resp.code == 200) {
				authorOptions.value = resp.data;
				// .list.map(item => ({
				//      label: `${item.counselorName} `,
				//      value: item.id

			} else {
				ElMessage.error('查询失败');
			}
			console.log(resp);
		})
	};
	// 动态标题
	const title = ref('');
	// 控制对话框是否显示
	const dialogVisible = ref(false);
	const dialogVisibleCheck = ref(false);
	// 新增和修改数据集
	const counselorData = ref({
		counselorId: '',
		content: '',
		id: '',
		intro: '',
		title: '',
		briefImageUrl: '',
	})

	const cancle = () => {
		console.log('你点击了取消按钮');
		counselorData.value = {
			counselorId: '',
			content: '',
			id: '',
			intro: '',
			briefImageUrl: '',
			title: ''
		}
		dialogVisible.value = false;
	}
	const cancleCheck = () => {

		console.log('你点击了关闭按钮');
		counselorData.value = {
			counselorId: '',
			content: '',
			id: '',
			intro: '',
			briefImageUrl: '',
			title: ''
		}
		dialogVisibleCheck.value = false;

	}
	const add = () => {
		title.value = '新增';
		// 重置表单数据，确保所有字段都是空值
		counselorData.value = {
			counselorId: '',
			content: '',
			id: '',
			intro: '',
			title: '',
			briefImageUrl: '' // 确保这个字段被初始化
		}
		dialogVisible.value = true;
	}

	const confirm = () => {
		// 验证表单数据
		if (!counselorData.value.title) {
			ElMessage.error('请输入文章标题');
			return;
		}

		if (!counselorData.value.content) {
			ElMessage.error('请输入文章内容');
			return;
		}

		if (!counselorData.value.counselorId) {
			ElMessage.error('请选择作者');
			return;
		}

		if (counselorData.value.id) {
			// 修改操作
			axios.put('welfareCenter', counselorData.value)
				.then((resp) => {
					if (resp.code == 200) {
						ElMessage.success('修改成功');
					} else {
						ElMessage.error('修改失败');
					}
					queryDataList();
					dialogVisible.value = false;
				})
				.catch((error) => {
					ElMessage.error('修改请求失败：' + error.message);
					console.error(error);
				});
		} else {
			// 新增操作
			console.log('准备提交新增数据:', counselorData.value); // 调试用
			axios.post('welfareCenter', counselorData.value)
				.then((resp) => {
					console.log('新增响应:', resp); // 调试用
					if (resp.code == 200) {
						ElMessage.success('新增成功');
					} else {
						ElMessage.error('新增失败: ' + (resp.message || '未知错误'));
					}
					queryDataList();
					dialogVisible.value = false;
				})
				.catch((error) => {
					ElMessage.error('新增请求失败：' + error.message);
					console.error(error);
				});
		}
	}
	// const add = () => {
	//   title.value = '新增';
	//   dialogVisible.value = true;
	// }
	const edit = (row) => {
		title.value = "编辑";
		dialogVisible.value = true;
		counselorData.value = row;
		// console.log(row);//这样输出的是编辑的那一行的数据
	}
	const check = (row) => {
		title.value = "查看详情内容";
		dialogVisibleCheck.value = true;
		counselorData.value = row;
		// console.log(row);//这样输出的是编辑的那一行的数据
	}

	const remove = (id) => {
		// console.log(id);
		ElMessageBox.confirm(
				'此操作将永久删除，是否继续?',
				'提示', {
					confirmButtonText: '继续删除',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.delete(`welfareCenter/${id}`)
					.then((resp) => {
						if (resp.code == 200) {
							ElMessage.success('删除成功')

						} else {
							ElMessage.error('删除失败')

						}
						queryDataList()
					})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})

	}
	const batchRemove = () => {
		ElMessageBox.confirm(
				'此操作将永久删除，是否继续?',
				'提示', {
					confirmButtonText: '继续删除',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.delete('welfareCenter', {
						//ids:15,16
						params: {
							ids: multipleSelection.value.join(',')
						}
					})
					.then((resp) => {
						if (resp.code == 200) {
							ElMessage.success('删除成功')

						} else {
							ElMessage.error('删除失败')

						}
						queryDataList()
					})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})

	}




	onMounted(() => {
		fetchAuthors()
		queryDataList();
	})
</script>

<style scoped>
	.el-breadcrumb {
		border-bottom: 1px solid #eeeeee;
		padding-bottom: 20px;
	}

	.el-form {

		padding: 15px;
	}

	.simple {

		display: -webkit-box;
		-webkit-line-clamp: 2;
		/* 限制为两行 */
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		word-break: break-all;
		/* 长单词或URL换行 */

	}

	.el-pagination {
		margin-top: 15px;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}
</style>